package org.dragonnova.business.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.concurrent.TimeoutException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.dragonnova.business.model.IotSim;

import com.alibaba.fastjson.JSONObject;

/**
 * 物联网流量平台接口
 * 
 * @author haojinyu
 */
public class IotSimUtils {

	/**
	 * 查询卡号是否存在
	 */
	public static String checkTerminal(IotSim iotSim) {
		String checkTerminalUrl = "https://api.ext.m-m10086.com/open/Help/CheckTerminal";
		String jsonParam = JSONObject.toJSONString(iotSim);
		return IotSimUtils.requestIotSim(checkTerminalUrl, jsonParam);
	}

	/**
	 * 查单卡详情 传入卡号(ICCID、SIM、IMSI)返回卡基本信息，状态，已用量及剩余服务等数据。
	 */
	public static String terminalDetail(IotSim iotSim) {
		String terminalDetailUrl = "https://api.ext.m-m10086.com/open/cmcc/TerminalDetail";
		JSONObject jsonObj = (JSONObject) JSONObject.toJSON(iotSim);
		String[] options = new String[]{"package","packagesn"};
		jsonObj.put("optional", options);
		return IotSimUtils.requestIotSim(terminalDetailUrl, jsonObj.toJSONString());
	}
	
	/**
	 * 卡续费时需要选择指定套餐，该卡可续套餐通过调用此接口返回
	 */
	public static String renewalsPackageList(IotSim iotSim) {
		String renewalsPackageUrl = "https://api.ext.m-m10086.com/open/cmcc/RenewalsPackageList";
		JSONObject jsonObj = (JSONObject) JSONObject.toJSON(iotSim);
		String[] options = new String[]{"price","orig_price","package_info"};
		jsonObj.put("optional", options);
		return IotSimUtils.requestIotSim(renewalsPackageUrl, jsonObj.toJSONString());
	}
	
	/**
	 * 卡续费请求
	 */
	public static String renewals(IotSim iotSim, Integer packageSn) {
		String renewalsUrl = "https://api.ext.m-m10086.com/open/cmcc/Renewals";
		JSONObject jsonObj = (JSONObject) JSONObject.toJSON(iotSim);
		jsonObj.put("packagesn", packageSn);
		jsonObj.put("user_ordersn", "1a2b3c4d5e6f7g8h9i");
		return IotSimUtils.requestIotSim(renewalsUrl, jsonObj.toJSONString());
	}
	
	
	/**
	 * 获取套餐支付二维码图片
	 */
	public static String packageQrcode(IotSim iotSim, Integer packageSn) {
		String qrcodeUrl = "https://api.ext.m-m10086.com/open/cmcc/PackageQrcode";
		JSONObject jsonObj = (JSONObject) JSONObject.toJSON(iotSim);
		jsonObj.put("packagesn", packageSn);
		
		return IotSimUtils.requestIotSim(qrcodeUrl, jsonObj.toJSONString());
	}
	
	/**
	 * 订单查询
	 */
	public static String orderQuery(IotSim iotSim, String ordersn) {
		String qrcodeUrl = "https://api.ext.m-m10086.com/open/cmcc/OrderQuery";
		JSONObject jsonObj = (JSONObject) JSONObject.toJSON(iotSim);
		jsonObj.put("ordersn", ordersn);
		return IotSimUtils.requestIotSim(qrcodeUrl, jsonObj.toJSONString());
	}


	/**
	 * @param url
	 * @param jsonParam
	 * @return
	 */
	public static String requestIotSim(String url, String jsonParam) {
		return IotSimUtils.httpRequest(url, "POST", jsonParam);
	}

	/**
	 * 方法名：httpRequest</br>
	 * 详述：发送http请求</br>
	 * 创建时间：2016-1-5 </br>
	 * 
	 * @param requestUrl
	 * @param requestMethod
	 * @param outputStr
	 * @return 说明返回值含义
	 * @throws 说明发生此异常的条件
	 */
	public static String httpRequest(String requestUrl, String requestMethod, String jsonParam) {
		String resultStr = "";
		StringBuffer buffer = new StringBuffer();
		InputStream inputStream = null;
		HttpsURLConnection httpUrlConn = null;
		try {
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(5000);
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod)) {
				httpUrlConn.connect();
			} else {

			}
			if (null != jsonParam) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(jsonParam.getBytes("UTF-8"));
				outputStream.close();
			}
			int responseCode = httpUrlConn.getResponseCode();
			inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}

			bufferedReader.close();
			inputStreamReader.close();

			resultStr = buffer.toString();
			return resultStr;
		} catch (ConnectException ce) {
			ce.printStackTrace();
			return "{\"error\":\"" + ce.getMessage() + "\"}";
		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof SocketTimeoutException) {
				return "{\"error\":-2}";
			}
			return "{\"error\":\"" + e.getMessage() + "\"}";
		} finally {

			try {
				if (inputStream!=null) {
					inputStream.close();
				}
				inputStream = null;
			} catch (IOException e) {
				e.printStackTrace();
			}

			httpUrlConn.disconnect();
		}
	}

	/**
	 * #<!-- 物联网流量接口错误码-->  
	 */
	public static String getErrorStr(int error) {
		switch (error) {
		case 100001:
			return "卡号格式错误！";
		case 100002:
			return "卡号不存在！";
		case 100003:
			return "账号无权查看该卡！";
		case 100004:
			return "部分卡号不存在！";
		case 100005:
			return "部分卡号重复！";
		case 200001:
			return "userId不存在！";
		case 200002:
			return "签名失败！";
		case 300001:
			return "没有指定套餐权限！";
		case 300002:
			return "没有指定订单信息！";
		case 400001:
			return "续费失败！";
		case 400002:
			return "账户余额不足！";
		case 400003:
			return "订单创建失败！";
		case 400005:
			return "扣除帐户余额失败！";
		case 500001:
			return "无效的参数字段！";
		case 600001:
			return "无效的照片URL！";
		case 600002:
			return "照片规格不合法！";
		case 600003:
			return "已经通过实名认证！";
		case -2:
			return "连接超时";
		default:
			return "未知错误！";
		}
	}
}
